package com.mls.guardian.appst.chain.excutor;

import com.mls.guardian.appst.chain.TaskExecutor;
import com.mls.guardian.appst.chain.TaskInvoker;
import com.mls.guardian.appst.chain.TaskResult;
import com.mls.guardian.common.FileUtil;
import com.mls.guardian.dataobj.ModuleMessage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

/**
 * Created by 2014-400 on 2015-11-16.
 * 1、停止dubbo服务
 * 2、从备份目录复制jar文件替换目标目录jar文件
 * 3、重启dubbo服务
 */
public class RestoreJarExcutor implements TaskExecutor {
    private static final Logger log = LoggerFactory.getLogger(RestoreJarExcutor.class);

    @Override
    public TaskResult exec(TaskInvoker invoker) {
        TaskResult result = null;
        try {
            log.info("----开始restore jar----");
            //替换jar文件
            for (ModuleMessage item : invoker.getModuleList()) {
                log.info("----restore jar[{}]----", item.getModuleName());
                String sourceFile = invoker.getConfig().getBackupDest() + File.separator + invoker.getProject().getProjectName() + File.separator + invoker.getVersionTag() + File.separator + item.getModuleName() + ".jar";
                String targetFile = invoker.getConfig().getMoveDest() + File.separator + invoker.getProject().getProjectName() + File.separator + item.getModuleName() + ".jar";

                if (Files.exists(Paths.get(sourceFile))) {
                    Files.copy(Paths.get(sourceFile), Paths.get(targetFile), StandardCopyOption.REPLACE_EXISTING);
                }
            }
            //替换lib目录
            String sourceFolder = invoker.getConfig().getBackupDest() + File.separator + invoker.getProject().getProjectName() + File.separator + invoker.getVersionTag() + File.separator + "lib";
            String targetFolder = invoker.getConfig().getMoveDest() + File.separator + invoker.getProject().getProjectName() + File.separator + "lib";
            if (Files.exists(Paths.get(sourceFolder))) {
                if (Files.exists(Paths.get(targetFolder))) {
                    FileUtil.deleteFolder(targetFolder);
                }
                FileUtil.copyFolder(sourceFolder, targetFolder, true);
            }

            result = new TaskResult();
            result.setSuc(true);
        } catch (Exception e) {
            result = new TaskResult();
            result.setSuc(false);
            result.setError(e.getMessage());
            e.printStackTrace();
        } finally {
            log.info("----结束restore jar[{}]----", result.isSuc());
        }

        if (result.isSuc() == true) {
            return invoker.invoke();
        }

        return result;
    }
}
